package com.iptv.grape.video;


import android.content.Context;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Message;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;

import com.iptv.grape.MediaPlayerActivity;
import com.iptv.grape.bu.AppConfig;
import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.util.AppConstant;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.CommUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class XMediaPlayer implements SurfaceHolder.Callback, MediaPlayer.OnErrorListener, WorkThread.IWork,
        MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener{
    // 播放绘制的表面对象
    private SurfaceView surfaceView;
    // 绘制的表面对象的句柄
    private SurfaceHolder surfaceHolder;
    // 进度条
    private ProgressBar progressBar;
    //private FrameLayout fl_SurfaceView;
    // MediaPlayer对象
    private MediaPlayer mediaPlayer;
    // 上下文
    private Context context;
    // 当前的播放地址
    private String livePalyUlr;
    // 是否存在播放请求
    private boolean isCalllPlay = false;

    // 当前小窗口的位置
    private VideoSize videoSize;
    // 最后的播放进度
    private int lastSeek = -1;
    // 报告用工作线程
    private WorkThread workThread;

    // 事件监听者的存放列表
    private ArrayList<IPlayerListener> eventListenerList = new ArrayList<IPlayerListener>();
    // 添加事件监听者
    public void setOnPlayerListener(IPlayerListener playerListener){
        eventListenerList.add(playerListener);
    }
    // 移除事件监听者
    public void removeListener(IPlayerListener playerListener){
        if(!eventListenerList.isEmpty()){
            eventListenerList.remove(playerListener);
        }

    }

    public int getCurrentPosition(){
        try {
            if (mediaPlayer != null) {
                return mediaPlayer.getCurrentPosition();
            }
            return 0;
        }
        catch (Exception e){
            return 0;
        }
    }

    // 引发事件
    private void triggerEvent(String eventName){
        switch (eventName){
            case "stop":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        if(mediaPlayer != null) {
                            item.onStop(getCurrentPosition());
                        }
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case "playing":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.onPlaying();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case "pause":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.onPlayPause();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case "error":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.onError();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case "progress":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.onProgress(mediaPlayer.getCurrentPosition());
                    }
                    catch (Exception e){
                        e.printStackTrace();
                        AppLog.getCurLog().out(e.getMessage());
                    }
                }
                break;
            case "intoFullScreen":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.onIntoFullScreen();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case "quitFullScreen":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.onQuitFullScreen();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case "playCompletion":
                for (IPlayerListener item:eventListenerList) {
                    try{
                        item.playCompletion();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    // 是否可以播放
    private boolean canPlayer;

    // 构造函数
    public XMediaPlayer(SurfaceView surfaceView, ProgressBar progressBar){
        this.surfaceView = surfaceView;
        this.progressBar = progressBar;
        this.surfaceHolder = surfaceView.getHolder();
        this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //this.surfaceHolder.setFixedSize(176, 144);//设置分辨率 Qcif(176×144）
        //this.surfaceHolder.setFixedSize(352, 288);//设置分辨率 CIF(352×288）
        //this.surfaceHolder.setFixedSize(704, 288);//设置分辨率 HALF D1(704×288）
        //this.surfaceHolder.setFixedSize(1280, 720);//D4：720p格式（750p）
        this.surfaceHolder.setFixedSize(1920, 1080);//设置分辨率 D1(704×576）
        this.surfaceHolder.setKeepScreenOn(true);
        // 设置surface回调
        this.surfaceHolder.addCallback(this);
        this.workThread = new WorkThread(1000,this);



    }
    // 内部的播放方法
    public void playVideo(Context context,String livePalyUlr) {
        synchronized(XMediaPlayer.class) {
            if (this.canPlayer) {
                // 初始化MediaPlayer
                mediaPlayer = new MediaPlayer();
                // 重置mediaPaly,建议在初始滑mediaplay立即调用。
                // mediaPlayer.reset();
                // 设置声音效果
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                // 设置播放完成监听
                mediaPlayer.setOnCompletionListener(this);
                // 设置媒体加载完成以后回调函数。
                mediaPlayer.setOnPreparedListener(this);
                // 错误监听回调函数
                mediaPlayer.setOnErrorListener(this);
                // 设置缓存变化监听
                //mediaPlayer.setOnBufferingUpdateListener(this);


                Uri uri = null;
                if (AppConstant.IsUseRealPlayUrl) {
                    uri = Uri.parse(livePalyUlr);
                } else {
                    uri = Uri.parse(CommUtil.GetPlayUrl(livePalyUlr));
                }
                try {
                    // 双重检查
                    if (this.canPlayer && mediaPlayer != null) {
                        // mediaPlayer.reset();
                        // 保留最后一帧视频
                        //MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                        //bitmap = mediaMetadataRetriever.getFrameAtTime(i, MediaMetadataRetriever.OPTION_CLOSEST);
                        mediaPlayer.setDataSource(context, uri);
                        AppLog.getCurLog().out(livePalyUlr);
                        // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
                        mediaPlayer.prepareAsync();
                        //mediaPlayer.setDisplay(surfaceHolder);
                        // 设置surfaceView保持在屏幕上
                        //mediaPlayer.setScreenOnWhilePlaying(true);
                        //mediaPlayer.prepare();
                        //mediaPlayer.start();
                        AppLog.getCurLog().out("XMediaPlayer----playVideo");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    AppLog.getCurLog().out(e.getMessage());
                }
            }
        }
    }

    // surfaceView被创建
    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        AppLog.getCurLog().out("XMediaPlayer----surfaceCreated");
        this.canPlayer = true;
        if(isCalllPlay && this.context!= null && this.livePalyUlr != null){
            this.playVideo(this.context,this.livePalyUlr);
        }
    }


    //boolean seekBarAutoFlag = false;
    // 缓冲完成
    // 线程冲突 BUG 后期修改
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        if(this.canPlayer && mediaPlayer != null)
        {
            AppLog.getCurLog().out("XMediaPlayer----onPrepared");
            mediaPlayer.setDisplay(surfaceHolder);
            // 设置surfaceView保持在屏幕上
            mediaPlayer.setScreenOnWhilePlaying(true);
            // 播放视频
            //mediaPlayer.seekTo(5000);

            if(lastSeek > 0 && lastSeek < mediaPlayer.getDuration()){
                if(mediaPlayer.getDuration() - lastSeek < 1000){
                    lastSeek = 0;
                }
                mediaPlayer.seekTo(lastSeek);
            }
            rePlayCount = 0;
            mediaPlayer.start();

            this.progressBar.setVisibility(View.GONE);
            // 设置显示到屏幕
            surfaceHolder.setKeepScreenOn(true);
            triggerEvent("playing");

            if(workThread.isRunning() == false){
                if(this.seekbar != null) {
                    seekbar.setProgress(0);
                    seekbar.setMax(mediaPlayer.getDuration());
                    seekbar.setKeyProgressIncrement(1000 * AppConfig.getAppConfig().getBackLiveModeKeyProgressIncrement());
                }
                //thread.start();
                workThread.start();
            }

        }

    }


    /**
     * 滑动条变化线程
     */
    @Override
    public void doWork(Object args) {
        try {
            if (seekbar != null && null != mediaPlayer && mediaPlayer.isPlaying()) {
                seekbar.setProgress(mediaPlayer.getCurrentPosition());
            }
            triggerEvent("progress");
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }


    // SurfaceView的大小改变
    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {

    }

    // surfaceView销毁
    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        AppLog.getCurLog().out("XMediaPlayer----surfaceDestroyed");
        this.canPlayer = false;
        this.isCalllPlay = false;
        // 如果MediaPlayer没被销毁，则销毁mediaPlayer
        //this.stop();
    }
    // 播放错误
    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
        triggerEvent("error");
        AppLog.getCurLog().out("MediaPlayer---OnError - Error code: " + what + " Extra code: " + extra);
        switch (what) {
            case -1004:
                AppLog.getCurLog().out("MEDIA_ERROR_IO");
                break;
            case -1007:
                AppLog.getCurLog().out("MEDIA_ERROR_MALFORMED");
                break;
            case 200:
                AppLog.getCurLog().out("MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                break;
            case 100:
                AppLog.getCurLog().out("MEDIA_ERROR_SERVER_DIED");
                break;
            case -110:
                AppLog.getCurLog().out("MEDIA_ERROR_TIMED_OUT");
                break;
            case 1:
                AppLog.getCurLog().out("MEDIA_ERROR_UNKNOWN");
                break;
            case -1010:
                AppLog.getCurLog().out("MEDIA_ERROR_UNSUPPORTED");
                break;
        }

        switch (extra) {
            case 800:
                AppLog.getCurLog().out("MEDIA_INFO_BAD_INTERLEAVING");
                break;
            case 702:
                AppLog.getCurLog().out("MEDIA_INFO_BUFFERING_END");
                break;
            case 701:
                AppLog.getCurLog().out("MEDIA_INFO_METADATA_UPDATE");
                break;
            case 802:
                AppLog.getCurLog().out("MEDIA_INFO_METADATA_UPDATE");
                break;
            case 801:
                AppLog.getCurLog().out("MEDIA_INFO_NOT_SEEKABLE");
                break;
            case 1:
                AppLog.getCurLog().out("MEDIA_INFO_UNKNOWN");
                break;
            case 3:
                AppLog.getCurLog().out("MEDIA_INFO_VIDEO_RENDERING_START");
                break;
            case 700:
                AppLog.getCurLog().out("MEDIA_INFO_VIDEO_TRACK_LAGGING");
                break;
        }
        return false;
    }


    // 小窗口播放
    public void play(Context context,String livePalyUlr,VideoSize videoSize){
        this.surfaceView.setVisibility(View.VISIBLE);
        this.videoSize = videoSize;
        this.surfaceView.setLayoutParams(videoSize.getLayoutParams());
        this.progressBar.setLayoutParams(videoSize.getProbarLayoutParams(false));
        this.context = context;
        this.livePalyUlr = livePalyUlr;
        this.isCalllPlay = true;

        this.progressBar.setVisibility(View.VISIBLE);
        if(this.canPlayer){
            this.isCalllPlay = false;
            this.playVideo(context,livePalyUlr);
        }
    }
    // 小窗口播放
    public void play(Context context,String livePalyUlr,VideoSize videoSize,boolean isLoop){
        this.surfaceView.setVisibility(View.VISIBLE);
        this.videoSize = videoSize;
        this.surfaceView.setLayoutParams(videoSize.getLayoutParams());
        this.progressBar.setLayoutParams(videoSize.getProbarLayoutParams(false));
        this.context = context;
        this.livePalyUlr = livePalyUlr;
        this.isCalllPlay = true;

        this.progressBar.setVisibility(View.VISIBLE);
        if(this.canPlayer){
            this.isCalllPlay = false;
            this.playVideo(context,livePalyUlr,isLoop);
        }
    }


    static int rePlayMaxCount = 3;
    private int rePlayCount = 0;
    public void rePlay(Context context){
        rePlayCount++;
        if(rePlayCount < rePlayMaxCount) {
            this.surfaceView.setVisibility(View.VISIBLE);
            this.isCalllPlay = true;
            this.context = context;
            if (this.canPlayer) {
                this.isCalllPlay = false;
                this.playVideo(context, livePalyUlr);
            }
        }
    }

    // 内部的播放方法
    public void playVideo(Context context,String livePalyUlr,boolean isLoop) {
        synchronized(XMediaPlayer.class) {
            if (this.canPlayer) {
                // 初始化MediaPlayer
                mediaPlayer = new MediaPlayer();
                // 重置mediaPaly,建议在初始滑mediaplay立即调用。
                // mediaPlayer.reset();
                // 设置声音效果
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                // 设置播放完成监听
                mediaPlayer.setOnCompletionListener(this);
                // 设置媒体加载完成以后回调函数。
                mediaPlayer.setOnPreparedListener(this);
                // 错误监听回调函数
                mediaPlayer.setOnErrorListener(this);
                mediaPlayer.setLooping(isLoop);
                // 设置缓存变化监听
                //mediaPlayer.setOnBufferingUpdateListener(this);


                Uri uri = null;
                if (AppConstant.IsUseRealPlayUrl) {
                    uri = Uri.parse(livePalyUlr);
                } else {
                    uri = Uri.parse(CommUtil.GetPlayUrl(livePalyUlr));
                }
                try {
                    // 双重检查
                    if (this.canPlayer && mediaPlayer != null) {
                        // mediaPlayer.reset();
                        // 保留最后一帧视频
                        //MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                        //bitmap = mediaMetadataRetriever.getFrameAtTime(i, MediaMetadataRetriever.OPTION_CLOSEST);
                        mediaPlayer.setDataSource(context, uri);
                        AppLog.getCurLog().out(livePalyUlr);
                        // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
                        mediaPlayer.prepareAsync();
                        //mediaPlayer.setDisplay(surfaceHolder);
                        // 设置surfaceView保持在屏幕上
                        //mediaPlayer.setScreenOnWhilePlaying(true);
                        //mediaPlayer.prepare();
                        //mediaPlayer.start();
                        AppLog.getCurLog().out("XMediaPlayer----playVideo");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    AppLog.getCurLog().out(e.getMessage());
                }
            }
        }
    }
    // 全屏换台播放
    public void play(Context context,String livePalyUlr){
        this.context = context;
        this.livePalyUlr = livePalyUlr;
        this.isCalllPlay = true;

        if(this.canPlayer){
            this.isCalllPlay = false;
            this.playVideo(context,livePalyUlr);
        }
    }

    public void fullScreenPlay(Context context,String livePalyUlr){
        this.fullScreen();
        this.play(context,livePalyUlr);
    }

    // 暂停
    public synchronized void pause(){
        if(this.mediaPlayer != null && this.mediaPlayer.isPlaying()) {
            this.mediaPlayer.pause();
            triggerEvent("pause");

        }
    }
    // 回复播放
    public synchronized void start(){
        if(this.mediaPlayer != null && !this.mediaPlayer.isPlaying()) {
            this.mediaPlayer.start();
            triggerEvent("playing");

        }
    }

    public boolean isPlaying(){
        if(this.mediaPlayer != null) {
            return this.mediaPlayer.isPlaying();
        }
        return false;
    }

    public int getDuration(){
        if(this.mediaPlayer != null) {
            return mediaPlayer.getDuration();
        }
        return 0;
    }


    // 全屏
    public void fullScreen(){
        this.surfaceView.setVisibility(View.VISIBLE);
        //this.progressBar.setVisibility(View.VISIBLE);
        this.surfaceView.setLayoutParams(VideoSize.getFullLayoutParams());
        this.progressBar.setLayoutParams(videoSize.getProbarLayoutParams(true));
        triggerEvent("intoFullScreen");
    }
    // 全屏
    public void setVideoSize(VideoSize videoSize){
        this.videoSize = videoSize;
    }

    // 退出全屏
    public void quitFullScreen(){
        this.surfaceView.setLayoutParams(this.videoSize.getLayoutParams());
        triggerEvent("quitFullScreen");
    }

    public void hiddView(){
        progressBar.setVisibility(View.GONE);
        surfaceView.setVisibility(View.GONE);
    }
    public void setPosition(VideoSize videoSize){
        this.surfaceView.setLayoutParams(videoSize.getLayoutParams());
        this.progressBar.setLayoutParams(videoSize.getProbarLayoutParams(false));
    }

    // 停止播放
    public void stop(){

        synchronized(XMediaPlayer.class) {
            try {
                if (workThread.isRunning()) {
                    workThread.stop();
                }

                triggerEvent("stop");
                //this.canPlayer = false;
                if (mediaPlayer != null) {
                    mediaPlayer.release();
                    mediaPlayer = null;
                    lastSeek = -1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                AppLog.getCurLog().out(e.getMessage());
            }
        }
    }

    private SeekBar seekbar;
    public synchronized void setSeekbar(SeekBar seekbar){
        this.seekbar = seekbar;
        try {
            if (this.mediaPlayer != null && this.mediaPlayer.isPlaying()){
                this.seekbar.setProgress(0);
                this.seekbar.setMax(mediaPlayer.getDuration());
                this.seekbar.setProgress(mediaPlayer.getCurrentPosition());
                //if(!workThread.isRunning()){
                 //   workThread.run();
                //}
            }

        }
        catch (Exception e){

        }
    }

    public synchronized void seekTo(int seekToVal){
        try {
            if (this.mediaPlayer != null && this.mediaPlayer.isPlaying()) {
                this.mediaPlayer.seekTo(seekToVal);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void seekToVod(int lastSeek){
        this.lastSeek = lastSeek;
    }


    public synchronized void cleanSeekbar(){
        this.seekbar = null;
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {


        this.stop();
        this.triggerEvent("playCompletion");
    }
}
